const koa = require("koa");
const koabody = require("koa-body");
const helmet = require("koa-helmet");
const error = require('koa-json-error')
const comporess = require("koa-compress");
const static = require('koa-static')
const logger = require('koa-logger')
const jwt = require('koa-jwt')

const path = require("path");
const RouterInit = require('./router')
const logsUtil = require('./utils/logs.js');
const { secret } = require('./config/config')
const app = new koa();

app.use(helmet()); // 安全框架

app.use(comporess()); // 压缩响应数据，是后台响应更快

// 错误处理转json
app.use(error({
    postFormat: (e, { stack, ...rest}) => process.env.NODE_ENV === 'production'? rest : { stack , ...rest}
}))


// 配置文件上传和·解析请求参数
app.use(
  koabody({
    multipart: true, // 开启多文件上传
    formidable: {
      maxFileSize: 100 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
      //uploadDir: 可以填写一个路径，不填写默认为 os.tmpDir()
    },
  })
);

// 配置日志文件
app.use(async (ctx, next) => {
  const start = new Date();
  let intervals;
  try {
    await next();
    intervals = new Date() - start;
    logsUtil.logResponse(ctx, intervals);
  } catch (error) {
    intervals = new Date() - start;
    logsUtil.logError(ctx, error, intervals);
  }
});

app.use(logger()) // 控制台日志输出

//状态码监听
app.use((ctx, next) =>{
    return next().catch((err) => {
      if (401 == err.status) {
         ctx.body = {
             message: '你没有权限',
             statusCode: 401
        }
      } else {
        throw err;
      }
    });
});

// 配置请求头
app.use(async (ctx, next)=> {
    console.log(ctx.request.body)
      ctx.set('Access-Control-Allow-Origin', '*');
      ctx.set('Access-Control-Allow-Headers', '*');
      ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
      ctx.set("Access-Control-Allow-Headers", "Content-Type,Access-Token"),
     ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
      if (ctx.method == 'OPTIONS') {
           ctx.body = 200; 
      } else {
        await next();
      }
  })

app.use(jwt({ secret: secret}).unless({ path: ['/admin/login', '/admin/register','/common/getcaptcha']}))


app.use(static(path.join(__dirname, "public"))); // 配置服务静态资源目录

RouterInit(app) // 加载路由


app.listen(8000, (err) => {
  if (err) throw err;
  console.log("服务运行在3006端口");
});
